package c926.xiaoduyun.xiaodu.task;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.workflow.MessageCenterServiceHelper;
import kd.bos.workflow.engine.msg.info.MessageInfo;
import kd.sdk.plugin.Plugin;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Stream;

/**
 * 后台任务插件
 */
public class DisApplyBillTimeOutPlugin extends AbstractTask implements Plugin {

    /*
     * 定时任务
     * @Description: 如果过了申请进入时间的第二天零点还没开始消毒，
     * 则单据自动关闭（状态为废弃），且发送消息（消息中心通知和邮件）
     * 提示员工消毒申请已过期。
     */

    /**
     * 默认的年月日的格式. yyyy-MM-dd
     */
    public static final String PATTEN_DEFAULT_YMD = "yyyy-MM-dd";

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        // 查询申请人员单的单据状态为暂存，已审核，消毒中
        String[] billstatus = new String[]{"A", "C", "D"};
        QFilter qFilter = new QFilter("billstatus", QCP.in, billstatus);
        DynamicObject[] dynamicObjects = BusinessDataServiceHelper.load("c926_xiaoduapply", "billno,c926_applyuser," +
                "billstatus, c926_applyintime,c926_xiaodurecord", qFilter.toArray());
        Stream<DynamicObject> dynamicObjectStream = Arrays.stream(dynamicObjects).filter(dynamicObject -> {
            // 查询申请人员单的申请时间与当前时间是否小一天
            Date date = dynamicObject.getDate("c926_applyintime");
            // 当前时间
            Date now = new Date();
            SimpleDateFormat sf = new SimpleDateFormat(PATTEN_DEFAULT_YMD);
            //获取今天的日期
            String nowDay = sf.format(now);
            //对比的时间
            String day = sf.format(date);
            return day.compareTo(nowDay) < 0;
        });

        dynamicObjectStream.forEach(dynamicObject -> {
            //人员申请单状态改为废弃
            dynamicObject.set("billstatus", "E");
            OperationResult result = SaveServiceHelper.saveOperate("c926_xiaoduapply",
                    new DynamicObject[]{dynamicObject}, OperateOption.create());
            if (result.isSuccess()) {
                //消毒记录单改为废弃
                String record = dynamicObject.getString("c926_xiaoduid");
                if (!"".equals(record)) {
                    QFilter recordFilter = new QFilter("billno", QCP.equals, record);
                    DynamicObject recordDynamicObject = BusinessDataServiceHelper.loadSingle("c926_xiaodurecord",
                            "billstatus", recordFilter.toArray());
                    recordDynamicObject.set("billstatus", "C");
                    SaveServiceHelper.saveOperate("c926_xiaodurecord", new DynamicObject[]{recordDynamicObject},
                            OperateOption.create());
                }
                //发送消息
                sendMassage(dynamicObject);
            }
        });
    }

    public void sendMassage(DynamicObject dynamicObject) {
        // 消息通知
        // 发送站内消息和邮件消息
        MessageInfo messageInfo = new MessageInfo();
        // 消息标题
        LocaleString title = new LocaleString();
        title.setLocaleValue_zh_CN("员工消毒申请已过期");
        messageInfo.setMessageTitle(title);

        // 消息内容
        LocaleString content = new LocaleString();
        String contentString =
                "亲爱的棕熊工厂员工：" + dynamicObject.getString("c926_applyuser.name") +
                        "<br><b>你提交的编号为：" + dynamicObject.getString("billno")
                        + "的员工消毒申请单已超期并自动关闭，如还需进入车间，请重新发起申请</b><br>";
        content.setLocaleValue_zh_CN(contentString);
        messageInfo.setMessageContent(content);

        List<Long> ids = new ArrayList<>();
        ids.add(dynamicObject.getLong("c926_applyuser.id"));
        messageInfo.setUserIds(ids);
        messageInfo.setType(MessageInfo.TYPE_WARNING);
        messageInfo.setTag("员工消毒申请过期通知");
        //站内设置电子邮箱消息
        messageInfo.setOperation("audit");
        messageInfo.setPubaccNumber("flowassist");
        messageInfo.setType("email");
        //发送消息
        MessageCenterServiceHelper.sendMessage(messageInfo);
    }
}


